package com.sfh.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.plugin.activerecord.Page;
import com.sfh.base.BaseController;
import com.sfh.base.ReturnData;
import com.sfh.base.util.StringUtil;
import com.sfh.controller.rsp.RspMessage;
import com.sfh.controller.rsp.RspNote;
import com.sfh.controller.task.TaskMassNoteSize;
import com.sfh.controller.task.TaskNoteRead;
import com.sfh.controller.task.TaskUserWealthCharm;
import com.sfh.req.ReqCityPage;
import com.sfh.req.ReqIndex;
import com.sfh.req.ReqMassNote;
import com.sfh.req.ReqMessage;
import com.sfh.req.ReqNoteAdd;
import com.sfh.req.ReqNoteDel;
import com.sfh.req.ReqNoteFabulous;
import com.sfh.req.ReqNotePageMsg;
import com.sfh.req.ReqNoteQuery;
import com.sfh.req.ReqNoteSearch;
import com.sfh.req.ReqPage;
import com.sfh.req.ReqUserNote;
import com.sfh.service.Const;
import com.sfh.service.model.FileResModel;
import com.sfh.service.model.MessageModel;
import com.sfh.service.model.NoteModel;
import com.sfh.service.model.table.MessageTable;
import com.sfh.service.model.table.NoteTable;
import com.sfh.service.util.SQLHelp;

/***
 * 话题
 * 
 * @author DELL
 *
 */
public class NoteController extends BaseController {
	/***
	 * [APP 首页使用]推荐话题 4,
	 */
	public void queryHomeRecomNote() {
		try {
			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) ORDER BY %s,%s,%s DESC LIMIT %d,%d",
					NoteTable.Table,
					NoteTable.id, 
					NoteTable.id, 
					NoteTable.Table, 
					NoteTable.msgSize,
					NoteTable.fabulousSize, 
					NoteTable.readiSize, 
					index * 4,
					4);

			List<NoteModel> list = NoteModel.NOTE.find(sql);

			List<RspNote> page2 = this.handerUserAndMessageList(list);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * [APP 首页使用]热门 话题 6
	 */
	public void queryHomeHotNote() {
		try {

			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) ORDER BY %s DESC LIMIT %d,%d",
					NoteTable.Table, 
					NoteTable.id, 
					NoteTable.id, 
					NoteTable.Table, 
					NoteTable.readiSize, 
					index*6,
					 6);

			List<NoteModel> list = NoteModel.NOTE.find(sql);

			List<RspNote> page2 = this.handerUserAndMessageList(list);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * [APP 首页使用]最新话题 6
	 */
	public void queryHomeNewNote() {
		try {
			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) ORDER BY %s DESC LIMIT %d,%d",
					NoteTable.Table,
					NoteTable.id, 
					NoteTable.id, 
					NoteTable.Table, 
					NoteTable.time, 
					index * 6,
					 6);

			List<NoteModel> list = NoteModel.NOTE.find(sql);

			List<RspNote> page2 = this.handerUserAndMessageList(list);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}

	}

	/***
	 * [APP 首页使用]VIP 话题 9
	 */
	public void queryHomeVIPNote() {
		try {
			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) AND note_vip=1 ORDER BY %s LIMIT %d,%d",
					NoteTable.Table, 
					NoteTable.id, 
					NoteTable.id, 
					NoteTable.Table, 
					NoteTable.id, 
					index*9,
					9);

			List<NoteModel> list = NoteModel.NOTE.find(sql);

			List<RspNote> page2 = this.handerUserAndMessageList(list);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}

	}

	/***
	 * 福利
	 */
	public void pageNoteWelfare() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.addWhereEqualTo(NoteTable.vip, 1);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = this.handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 同城话题【分页】 请求参数{@link ReqPage}
	 * 
	 */
	public void pageNoteCity() {
		try {
			ReqCityPage req = this.getRequestObject(ReqCityPage.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.sore("desc", NoteTable.msgSize, NoteTable.fabulousSize, NoteTable.readiSize);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = this.handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 综合话题【分页】 请求参数{@link ReqPage}
	 * 
	 */
	public void pageNote() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.sore("desc", NoteTable.msgSize, NoteTable.fabulousSize, NoteTable.readiSize);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = this.handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	public void pageNoteSearch() {
		try {
			ReqNoteSearch req = this.getRequestObject(ReqNoteSearch.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			
			String like = this.getEncoder(req.getContent());
			sqlHelp.addWhereMatches(like,NoteTable.content, NoteTable.lable);
	
			
			sqlHelp.sore("desc", NoteTable.msgSize);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = this.handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}
	/***
	 * 当前用户的发布话题【分页】请求参数{@link ReqPage}
	 * 
	 */
	public void pageUserNote() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.addWhereEqualTo(NoteTable.userId, req.getUserId());
			sqlHelp.sore("desc", NoteTable.time);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 查看其它用户的发布话题【分页】请求参数{@link ReqUserNote}
	 * 
	 */
	public void pageOtherUserNote() {
		try {
			ReqUserNote req = this.getRequestObject(ReqUserNote.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.addWhereEqualTo(NoteTable.userId, req.getLookUserId());
			sqlHelp.sore("desc", NoteTable.time);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 最新话题【分页】 请求参数{@link ReqPage}
	 * 
	 * 
	 */
	public void pageRecently() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.sore("desc", NoteTable.time);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 最新排序 话题【社区】【分页】 请求参数{@link ReqMassNote}
	 * 
	 * 
	 */
	public void massNoteRecentlyPage() {
		try {
			ReqMassNote req = this.getRequestObject(ReqMassNote.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.addWhereEqualTo(NoteTable.massId, req.getMassId());
			sqlHelp.sore("desc", NoteTable.time);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());
			Page<RspNote> page2 = handerUserAndMessageList(req, page);

			System.out.println("最新排序 话题【社区】");
			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 综合排序 话题【社区】【分页】 请求参数{@link ReqMassNote}
	 * 
	 * 
	 */
	public void massNotePage() {
		try {
			ReqMassNote req = this.getRequestObject(ReqMassNote.class);
			SQLHelp sqlHelp = new SQLHelp(NoteTable.Table);
			sqlHelp.addWhereEqualTo(NoteTable.massId, req.getMassId());

			sqlHelp.sore("desc", NoteTable.msgSize, NoteTable.fabulousSize, NoteTable.readiSize);

			Page<NoteModel> page = NoteModel.NOTE.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			Page<RspNote> page2 = handerUserAndMessageList(req, page);

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 赞 请求参数{@link ReqNoteFabulous}
	 */
	public void addFabulous() {
		try {
			ReqNoteFabulous req = this.getRequestObject(ReqNoteFabulous.class);
			NoteModel note = NoteModel.NOTE.findById(req.getNoteId());

			if (note == null) {
				this.renderJson(ReturnData.error(100, "未查询到相关信息"));
				return;
			}
			NoteModel newNoteModel = new NoteModel();
			newNoteModel.setId(req.getNoteId());
			newNoteModel.setFabulousSize(note.getFabulousSize() + 1);
			if (newNoteModel.update()) {
				System.out.println("点赞 == 成功");
				// 被点赞人魅力 点赞人获得财力
				this.putTask(new TaskUserWealthCharm(note.getUserId(), Const.CHARM_NOTE_FA, Const.WEALTH_NOTE_FA));

			}
			this.renderJson(ReturnData.ok(true));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 评论 请求参数 {@link ReqMessage}
	 */
	public void addMessage() {
		try {
			ReqMessage req = this.getRequestObject(ReqMessage.class);
			if (StringUtil.isEmpty(req.getContent())) {
				this.renderJson(ReturnData.error(100, "评论内容不能为空"));
				return;
			}
			NoteModel note = NoteModel.NOTE.findById(req.getNoteId());

			if (note == null) {
				this.renderJson(ReturnData.error(100, "评论失败"));
				return;
			}
			MessageModel message = new MessageModel();
			message.setNoteId(req.getNoteId());
			message.setUserId(req.getUserId());
			message.setContent(this.getEncoder(req.getContent()));

			message.setTime(new Date());
			message.setMassId(req.getMassId());

			if (message.save()) {

				// 增加消息数量
				this.putTask(new TaskNoteRead(req.getNoteId()));

				// 被评论人获取魅力值 评论人获取财力值
				this.putTask(new TaskUserWealthCharm(note.getUserId(), Const.CHARM_NOTE_MSG, Const.WEALTH_NOTE_MSG));

				this.renderJson(ReturnData.ok(true));
			} else {
				this.renderJson(ReturnData.error(101, "评论失败"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 新增话题
	 * 
	 * {@link ReqNoteAdd}
	 */
	public void addNote() {
		try {
			ReqNoteAdd req = this.getRequestObject(ReqNoteAdd.class);

			if (req.getUserId() <= 0) {
				this.renderJson(ReturnData.error(101, "请登录"));
				return;
			}

			final Date createTime = new Date();
			NoteModel note = new NoteModel();

			note.setVip(req.getVip());
			note.setUserId(req.getUserId());
			note.setContent(this.getEncoder(req.getContent()));
			note.setLable(this.getEncoder(req.getLable()));
			note.setTime(createTime);
			note.setWealth(req.getWealth());
			note.setVersion(1);
			note.setReadiSize(0);
			note.setMsgSize(0);
			note.setFabulousSize(0);

			if (req.getMassId() > 0) {
				note.setMassId(req.getMassId());
			}

			boolean success = note.save();

			if (success) {
				final long noteId = note.getId();
				for (String file : req.getImages()) {
					FileResModel daFile = new FileResModel();
					daFile.setUserId(req.getUserId());
					daFile.setRelationId(noteId);
					daFile.setPath(file);
					daFile.setTime(createTime);
					daFile.setVersion(1);
					daFile.save();
				}
			}

			if (success) {
				// 创建者魅力值-财力
				this.putTask(new TaskUserWealthCharm(req.getUserId(), Const.CHARM_NOTE_ADD, Const.WEALTH_NOTE_ADD));
				// 数量 社团话题数量
				if (req.getMassId() > 0) {
					this.putTask(new TaskMassNoteSize(req.getMassId(), 1));
				}

				this.renderJson(ReturnData.ok(true));

			} else {
				this.renderJson(ReturnData.error(101, "发布失败"));
			}

		} catch (Exception e) {
			System.out.println("新增 0" + e);
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 删除话题
	 * 
	 * {@link ReqNoteDel}
	 */
	public void delNote() {
		try {
			ReqNoteDel req = this.getRequestObject(ReqNoteDel.class);
			NoteModel note = NoteModel.NOTE.findById(req.getNoteId());
			if (note == null) {
				this.renderJson(ReturnData.error(101, "未查询到相关话题信息"));
				return;
			}

			if (note.getUserId() != req.getUserId()) {
				this.renderJson(ReturnData.error(102, "没有相关权限"));
				return;
			}

			long massId = note.getMassId();
			if (note.delete()) {

				// 处理 创建者 用户魅力值-财力
				this.putTask(new TaskUserWealthCharm(req.getUserId(), Const.CHARM_NOTE_DEL, Const.WEALTH_NOTE_DEL));
				
				// 处理，社团话题数量-1
				if (massId > 0) {
					this.putTask(new TaskMassNoteSize(massId, -1));
				}

				this.renderJson(ReturnData.ok(true));
			} else {
				this.renderJson(ReturnData.error(101, "删除失败"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 查询话题详情{@link ReqNoteQuery}
	 * 
	 * @param req
	 */
	public void queryNote() {

		try {
			ReqNoteQuery req = this.getRequestObject(ReqNoteQuery.class);
			NoteModel note = NoteModel.NOTE.findById(req.getNoteId());
			if (note != null) {

				this.renderJson(ReturnData.ok(RspNote.creaNote(note)));

			} else {
				this.renderJson(ReturnData.error(101, "未查询到相关话题信息"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}

	}

	/***
	 * 查询话题评论
	 * 
	 * @param req
	 */
	public void pageMessage() {
		try {
			ReqNotePageMsg req = this.getRequestObject(ReqNotePageMsg.class);
			SQLHelp sqlHelp = new SQLHelp(MessageTable.Table);
			sqlHelp.addWhereEqualTo(MessageTable.noteId, req.getNoteId());
			sqlHelp.sore("asc", MessageTable.time);

			Page<MessageModel> page = MessageModel.MESSAGE.paginate(req.getNowPage(), req.getPageSize(),
					sqlHelp.getSelect(), sqlHelp.buildFrom());

			List<RspMessage> pageList = new ArrayList<RspMessage>(10);
			List<MessageModel> list = page.getList();
			if (list != null) {

				for (MessageModel message : list) {
					pageList.add(RspMessage.createMessage(message));
				}
			}

			Page<RspMessage> page2 = new Page<RspMessage>(pageList, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow());

			this.renderJson(ReturnData.ok(page2));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 处理创建人图片路径
	 * 
	 * @param page
	 * @return
	 */
	private Page<RspNote> handerUserAndMessageList(ReqPage req, Page<NoteModel> page) {

		List<NoteModel> list = page.getList();
		if (list == null || list.isEmpty()) {
			return new Page<RspNote>();
		}

		List<RspNote> lNotes = new ArrayList<RspNote>(10);

		for (NoteModel model : list) {
			RspNote note = RspNote.creaNote(model);
			lNotes.add(note);
			this.putTask(new TaskNoteRead(note.getNoteId()));
		}
		return new Page<>(lNotes, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
	}

	/***
	 * 处理创建人图片路径
	 * 
	 * @param page
	 * @return
	 */
	private List<RspNote> handerUserAndMessageList(List<NoteModel> list) {

		if (list == null || list.isEmpty()) {
			return new ArrayList<RspNote>();
		}

		List<RspNote> lNotes = new ArrayList<RspNote>(10);

		for (NoteModel model : list) {
			RspNote note = RspNote.creaNote(model);
			lNotes.add(note);
			this.putTask(new TaskNoteRead(note.getNoteId()));
		}
		return lNotes;
	}
}
